﻿<%@ webhandler Language="C#" class="Upload" %>

/**
 * KindEditor ASP.NET
 *
 * 本ASP.NET程序是演示程序，建议不要直接在实际项目中使用。
 * 如果您确定直接使用本程序，使用之前请仔细确认相关安全设置。
 *
 */

using System;
using System.Collections;
using System.Web;
using System.IO;
using System.Globalization;
using LitJson;

public class Upload : IHttpHandler
{
	private HttpContext context;
    private Boolean IsThumbnail = false;
	public void ProcessRequest(HttpContext context)
	{
        
        
		String aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/") + 1);
		
		//文件保存目录路径
        String savePath = "../../../DataFile/";

		//文件保存目录URL
        String saveUrl = aspxUrl + "../../../DataFile/";
        string file_ContentType;

		//定义允许上传的文件扩展名
		Hashtable extTable = new Hashtable();
		extTable.Add("image", "jpg");

		//最大文件大小
		int maxSize = 1024000;
		this.context = context;

		HttpPostedFile imgFile = context.Request.Files["imgFile"];
        

        
        file_ContentType = imgFile.ContentType.ToLower();
        if (!file_ContentType.Contains("image/"))    
        {
            showError("格式不正确。请检查文件是否已损坏" + file_ContentType);

        }
		if (imgFile == null)
		{
			showError("请选择文件。");
		}

		String dirPath = context.Server.MapPath(savePath);
		if (!Directory.Exists(dirPath))
		{
			showError("上传目录不存在。");
		}

		String dirName = context.Request.QueryString["dir"];
		if (String.IsNullOrEmpty(dirName)) {
			dirName = "image";
		}
		if (!extTable.ContainsKey(dirName)) {
			showError("目录名不正确。");
		}

		String fileName = imgFile.FileName;
		String fileExt = Path.GetExtension(fileName).ToLower();

		if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
		{
			showError("上传文件大小超过限制。");
		}

		if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
		{
			showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。");
		}

		//创建文件夹
		dirPath += dirName + "/";
		saveUrl += dirName + "/";
		if (!Directory.Exists(dirPath)) {
			Directory.CreateDirectory(dirPath);
		}
		String ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
		dirPath += ymd + "/";
		saveUrl += ymd + "/";
		if (!Directory.Exists(dirPath)) {
			Directory.CreateDirectory(dirPath);
		}

		String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_fff", DateTimeFormatInfo.InvariantInfo) + fileExt;
		String filePath = dirPath + newFileName;

        /* 存储到服务器 */
		imgFile.SaveAs(filePath);


        /* 文件安全性验证 */
        try
        {
        string ServerPath = filePath;
        System.IO.FileStream fs = new System.IO.FileStream(ServerPath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
            string fileclass = "";
            //这里的位长要具体判断.
            byte buffer;

            buffer = r.ReadByte();
            fileclass = buffer.ToString();
            buffer = r.ReadByte();
            fileclass += buffer.ToString();


            r.Close();
            imgFile.InputStream.Close();
            if (fileclass == "255216")
            {
                IsThumbnail = true; /* 图片文件，可以进行图片压缩 */
            }
            else
            {
                FileInfo f = new FileInfo(ServerPath);
                f.Delete();
            }
        }
        catch (Exception ex) { showError("格式不正确。请检查文件是否已损坏\n" + "\n" + ex); }
        finally
        {
            imgFile.InputStream.Dispose();
            imgFile.InputStream.Close();
        }
        
        
        
        /* 图像文件的处理 */
        if (dirName == "image" && IsThumbnail)
        {
            string ServerFile="../../../DataFile/image/"+ymd+"/"+newFileName;
            Thumbnail.MakeThumbnail(context.Server.MapPath(ServerFile), context.Server.MapPath(ServerFile).Replace(fileExt, "__p" + fileExt), 720, 600, "W", 95);
            Thumbnail.MakeThumbnail(context.Server.MapPath(ServerFile), context.Server.MapPath(ServerFile).Replace(fileExt, "__p_p" + fileExt), 300, 1200, "W", 95);
        }

		String fileUrl = saveUrl + newFileName;


		Hashtable hash = new Hashtable();
		hash["error"] = 0;
        hash["url"] = fileUrl.Replace(fileExt, "_s" + fileExt);

    
		context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
		context.Response.Write(JsonMapper.ToJson(hash));
		context.Response.End();
        
	}

	private void showError(string message)
	{
		Hashtable hash = new Hashtable();
		hash["error"] = 1;
		hash["message"] = message;
		context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
		context.Response.Write(JsonMapper.ToJson(hash));
		context.Response.End();
	}

	public bool IsReusable
	{
		get
		{
			return true;
		}
	}
}
